package cn.lh.service.impl;

import cn.lh.dao.FileDao;
import cn.lh.entity.dto.FileDto;
import cn.lh.entity.req.FileReq;
import cn.lh.entity.vo.FileVo;
import cn.lh.exception.BusinessException;
import cn.lh.service.FileService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;

/**
 * <p>
 * 文件表 服务实现类
 * </p>
 *
 * @author linhong
 * @since 2023-12-22
 */
@Service
public class FileServiceImpl extends ServiceImpl<FileDao, FileDto> implements FileService {

    @Resource
    private FileDao fileDao;

    @Value("${upload.file.path}")
    private String uploadFilePath;

    @Override
    public String upload(MultipartFile uploadFile) {
        try {
            String s = uploadFile.getOriginalFilename().replaceAll("\\s*", "");
            String name = System.currentTimeMillis()+ "_" + uploadFile.getOriginalFilename().replaceAll("\\s*", "");
            String path = uploadFilePath + name;
            File file = new File(path);
            uploadFile.transferTo(file);
            FileDto dto = new FileDto();
            dto.setName(name);
            dto.setPath(path);
            save(dto);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return "上传成功";
    }

    @Override
    public void down(Integer fileId, HttpServletResponse response) throws Exception {
        FileDto fileDto = getById(fileId);
        if (fileDto == null) {
            throw new BusinessException("文件不存在");
        }
        File file = new File(fileDto.getPath());
        if (!file.exists()) {
            throw new BusinessException("文件不存在");
        }
        response.setContentType("application/force-download");
        response.setCharacterEncoding("utf-8");
        response.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileDto.getName(), "UTF-8"));
        byte[] buffer = new byte[1024];
        try (FileInputStream fis = new FileInputStream(file);
             BufferedInputStream bis = new BufferedInputStream(fis)) {
            OutputStream os = response.getOutputStream();
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
        }
    }

    @Override
    public PageInfo<FileVo> getList(FileReq req) {
        PageHelper.startPage(req.getPageNum(),req.getPageSize());
        List<FileVo> list = fileDao.getList(req.getFileName());
        PageInfo<FileVo> info = new PageInfo<>(list);
        return info;
    }
}
